#!/usr/bin/env bash
#! Encoding UTF-8
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

set -e

BIN_FILENAME=loki

GITHUB_URL=https://github.com/grafana/${BIN_FILENAME}/releases

DOWNLOADER=
if [[ -z "${DOWNLOAD_BASE_PATH}" ]] ; then
    LOCAL_PATH=$(dirname $0)
    TMP_ROOT=${LOCAL_PATH}/tmp
else
    LOCAL_PATH=${DOWNLOAD_BASE_PATH}/${BIN_FILENAME}
    mkdir -p ${LOCAL_PATH}
    TMP_ROOT=${DOWNLOAD_BASE_PATH}/tmp
fi

info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
waring(){
    echo "$(date +'%F %T') [WARING] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

# --- create tempory directory and cleanup when done ---
setup_tmp() {
    TMP_DIR=$(mktemp -p ${TMP_ROOT} -d -t exporter-install.XXXXXXXXXX)
    cleanup() {
        code=$?
        set +e
        trap - EXIT
        rm -rf ${TMP_DIR}
        [[ $code -eq 0 ]] || info "Download failed"
        exit $code
    }
    trap cleanup INT EXIT
}

get_release_version() {
  info "$0 Finding latest release"
  case $DOWNLOADER in
      curl)
          if [[ -n ${PROXY_URL} ]] ; then
              VERSION_PROGRAM=$(curl -x ${PROXY_URL} -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o/dev/null | sed -e 's|.*/||')
          else
              VERSION_PROGRAM=$(curl -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o/dev/null | sed -e 's|.*/||')
          fi

          ;;
      wget)
          VERSION_PROGRAM=$(wget -SqO /dev/null ${GITHUB_URL}/latest 2>&1 | grep Location | sed -e 's|.*/||')
          ;;
      *)
          fatal "Incorrect downloader executable '$DOWNLOADER'"
          ;;
  esac
}

verify_downloader() {
    # Return failure if it doesn't exist or is no executable
    [ -x "$(which $1)" ] || return 1

    # Set verified executable as our downloader program and return success
    DOWNLOADER=$1
    return 0
}
# --- download from github url ---
download() {
    [ $# -eq 2 ] || fatal 'download needs exactly 2 arguments'

    case $DOWNLOADER in
        curl)
            if [[ -n ${PROXY_URL} ]] ; then
                curl -x ${PROXY_URL} -o $1 -sfL $2
            else
                curl -o $1 -sfL $2
            fi
            ;;
        wget)
            wget -qO $1 $2
            ;;
        *)
            fatal "Incorrect executable '$DOWNLOADER'"
            ;;
    esac

    # Abort if download command failed
    [ $? -eq 0 ] || waring 'Download failed'
}

main(){

  verify_downloader curl \
    || verify_downloader wget \
    || fatal 'Can not find curl or wget for downloading files'
  setup_tmp

  get_release_version
  if [[ -z ${VERSION_PROGRAM} ]] ;then
    fatal "Incorrect downloader get version"
  fi
  HASH_URL=${GITHUB_URL}/download/${VERSION_PROGRAM}/SHA256SUMS

  download ${TMP_DIR}/sha256sum ${HASH_URL}
  TAR_TYPE="zip"
  mkdir -p ${LOCAL_PATH}
  for BIN_NAME in "loki" "logcli" "promtail" ; do
    for OS_VERSION in "linux-arm" "linux-arm64" "linux-amd64" ; do
      TAR_PACKET=${BIN_NAME}-${OS_VERSION}

      if [[ -f ${LOCAL_PATH}/${TAR_PACKET}-${VERSION_PROGRAM}.${TAR_TYPE} ]] ; then
          waring "Promgram \"${TAR_PACKET}-${VERSION_PROGRAM}.${TAR_TYPE}\" already exists ."
          continue
      fi

      DOWNLOAD_URL=${GITHUB_URL}/download/${VERSION_PROGRAM}/${TAR_PACKET}.${TAR_TYPE}
      download ${TMP_DIR}/${TAR_PACKET}.${TAR_TYPE} ${DOWNLOAD_URL}
      HASH_INSTALLED=$(sha256sum ${TMP_DIR}/${TAR_PACKET}.${TAR_TYPE} | awk '{print $1}')
      HASH_EXPECTED=$(grep " ${TAR_PACKET}.${TAR_TYPE}$" ${TMP_DIR}/sha256sum | awk '{print $1}')
      if [ "${HASH_EXPECTED}" != "${HASH_INSTALLED}" ]; then
        waring "Download sha256sum does not match ${HASH_EXPECTED}, got ${HASH_BIN}"
      else
        info "Promgram \"${TAR_PACKET}.${TAR_TYPE}\" download successs ."
        echo "${TAR_PACKET}.${TAR_TYPE} ${HASH_INSTALLED}" >> ${LOCAL_PATH}/${BIN_NAME}.sha256sum
        cp -f ${TMP_DIR}/${TAR_PACKET}.${TAR_TYPE} ${LOCAL_PATH}/${TAR_PACKET}-${VERSION_PROGRAM}.${TAR_TYPE}
      fi
    done
  done
}

main
